"""
启动脚本 - 自动初始化数据库并启动服务
"""
import subprocess
import sys
import os
from test_connection import test_database_connection
from init_db import init_database

def main():
    """主启动函数"""
    print("🐍 启动三江译舟后端API服务 (Python FastAPI)")
    print("=" * 60)
    
    # 1. 测试数据库连接
    print("1️⃣ 测试数据库连接...")
    if not test_database_connection():
        print("❌ 数据库连接失败，请检查配置后重试")
        return
    
    # 2. 初始化数据库表
    print("\n2️⃣ 初始化数据库表...")
    try:
        init_database()
    except Exception as e:
        print(f"❌ 数据库初始化失败: {e}")
        return
    
    # 3. 启动服务
    print("\n3️⃣ 启动FastAPI服务...")
    print("🌐 服务地址: http://localhost:8220")
    print("📚 Swagger文档: http://localhost:8220/docs")
    print("📖 ReDoc文档: http://localhost:8220/redoc")
    print("🔧 开发模式: 热重载已启用")
    print("🛑 按 Ctrl+C 停止服务")
    print("=" * 60)
    
    try:
        # 启动uvicorn服务
        subprocess.run([
            sys.executable, "-m", "uvicorn", 
            "main:app", 
            "--host", "0.0.0.0", 
            "--port", "8220", 
            "--reload"
        ])
    except KeyboardInterrupt:
        print("\n👋 服务已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")

if __name__ == "__main__":
    main()
